Beginner Trying To Learn About Validating Fields Before Submit In Javascript
Can someone please help me? I am trying to get the fields validated before submit and if fields are empty I need error message to show up. I have tried jquery but i want to learn
Solution 1:
Easy way to try Html 5...without JS
use REQUIRED in input field
<inputtype="text" name="username"id="username" required>
Solution 2:
you should use the validation function with the help of code write as
<script>functionvalidation(){
var elment1=document.getElementById('el1').value;
.......
........// same write code aboveif(EmptyVaue(elment1)){
document.getElementById('el1').innerHTML="Enter the value first ";
}
}
functionEmptyVaue(val){
if(val==""){
returntrue;
}
else{
returnfalse;
}
}
/* other validation can you write same for check number email etc by function */</script><formaction="youe_page_url.extn"onclick="return validation()"><div>
Enter value<inputtype="text"id="el1"><spanid="error"style="color:red"></span></div><inputtype="submit"value="submit"></form> `
Solution 3:
I have tried jquery but i want to learn the javascript way.
Okay!
When you're working with form and you want to validate the form then form submit
event should be better choice to use with input[type="submit"]
button.
var frm = document.querySelector('form'),
user = document.querySelector('#username'),
pwd = document.querySelector('#pw'),
err = document.querySelector('#error');
frm.addEventListener('submit', function(e) {
err.textContent = '';
if (user.value.trim() === '') {
err.textContent = 'Please fill user name.';
returnfalse;
}
if (pwd.value.trim() === '') {
err.textContent = 'Please use valid password.';
returnfalse;
}
});
<formaction='#'method='post'><p><labelfor="username">Username:</label><inputtype="text"name="username"id="username"></p><p><labelfor="pw">Password:</label><inputtype="password"name="pw"id="pw"></p><p><inputtype="submit"value="Submit"></p><!-- placeholder for response if form data is correct/incorrect --><pid="error"></p></form>
Post a Comment for "Beginner Trying To Learn About Validating Fields Before Submit In Javascript"