Reputation: 333
I am trying to validate a text input referencing a person's name.
I have 3 validations, depending on whether the input is too short, null or it is a number. The Validations works if there has been no input, or the input is too short, but the number validation does not work.
If the input is 123 -> Validation says CORRECTLY that only numbers are allowed.
If the input is s123 or 123s or 1s23 -> Validation says nothing about numbers.
function formValidation(){
var emp_lname = document.getElementById('last_name').value;
if(emp_lname.length <=2){
document.getElementById('last_name').style.borderColor = "red";
document.getElementById('last_name_errors').innerHTML="Last Name is way too short!!!";
if(emp_lname === ""){
document.getElementById('last_name').style.borderColor = "red";
document.getElementById('last_name_errors').innerHTML="Please enter a Last Name!!!";
}
returned_value = false;
}
if (/^\d+$/.test(document.getElementById('last_name').value)) {
document.getElementById('last_name').style.borderColor = "red";
document.getElementById('last_name_errors').innerHTML="Last Name must NOT contain numbers!!!";
returned_value = false;
}
return returned_value;
}
This is the exact output:
Correct:
Correct:
False:
EDIT: JSFiddle link : https://jsfiddle.net/vagg77/jv0ofnxr/
Upvotes: 0
Views: 40
Reputation: 249
I would change the last IF to:
if (document.getElementById('last_name').value.match( /(1|2|3|4|5|6|7|8|9|0)/ ) ) {
document.getElementById('last_name').style.borderColor = "red";
document.getElementById('last_name_errors').innerHTML="Last Name must NOT contain numbers!!!";
returned_value = false;
}
Upvotes: 1