javascript validation not working for only alphabetic values - javascript

I have used a javascript validation function to validate it. I've used it to see whether the text entered to the html textbox is alphabetic(No numeric characters allowed). The function is called during onkeyup and onblur. The only problem is even when numeric values or special characters are typed in the validation doesn't work. If I leave the field blank then it works(Displays that the field is left blank). Here's my javascript code:
function isAlphabetic(x,y){
var exp = /^[a-zA-Z]+$/;
var a = document.getElementById(y).value;
if(a=="" || a== null){
document.getElementById(x).innerHTML = "You cannot leave this feild empty";
return;
}
else if(a!="" && a!= null){
if(y.match(exp)){
document.getElementById(x).innerHTML = "";
return;
}
else{
document.getElementById(x).innerHTML = "Only enter alphabetic characters allowed";
return;
}
}
else{
return;
}

If you use y as an id of element, I suppose you shouldn't check it with your regexp. Instead you should check a:
if(a.match(exp)) {

You don't need JavaScript anymore for any of this. Use the pattern attribute on the input field and the browser won't let the user enter anything that doesn't match, and use required to prevent submitting the form with an empty value.
Also, do you really want only ASCII letters? (are spaces allowed? how about non-ASCII letters such as "é"?)

Related

must at least have number and characters regex

I still don't understand how to use regex and there is regex like this :
/^[a-zA-Z0-9\s]+$/
and i use it in javascript
$('#oldPass, #newPass, #confpass').keydown(function (e) {
var inputValue = e.key;
if(inputValue.match(/^[a-zA-Z0-9\s]+$/)){
return;
}else{
e.preventDefault();
}
});
it works, i can't type anything beside alphanumeric, but how can i make that the new password must contain combination number and characters?
Minimum of 8 letters with atleast one letter and number.
^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}
check this link for verification
https://regex101.com/r/DcxNSc/1

how to use regular expression in javascript

var pattern=/[A-za-z0-9]/;
if((fs.value||ls.value||ad1.value||ad2.value||pc.value||city.value||email.value)!=pattern)
{alert("fields not entered");
return false;}
else
return true;
Even after entering all the fields in the form, I get alert message "field not entered. Here fs,ls,ad1,ad2,email,pc and city are form field values
You need to take the values from those fields and run them thru the regex matching tool while passing the regex to that method.
var pattern=/[A-za-z0-9]/;
"string to check against regex pattern".match(pattern);
See more here

check input fields with javascript

i am using the following code to check if user doesnt input special characters in name
var regex = /^[a-zA-Z ]{2,50}$/;//check for only letters
var ctrl = document.getElementById('input1');//given name field
if(!regex.test(ctrl.value))
{
alert('Ensure field Name contains only letters[A-Z]');
return;
}
can someone please help to change regex so client can also enter JUST one (')(IF NEEDED) e.g O'Daniel.
also for phone no field limit user with only one +
Thanks in advance.
You don't have to cram all the logic into a single regexp. To check for apostrophes, simply do a separate check:
var apostrophes = ctrl.value.match(/'/g);
return !apostrophes || apostrophes.length < = 1;
Use the same logic to check for no more than one + in the phone number.

complete form validation using javascript,php

I am trying to validate the password using regex with function but its not working for me. can anyone take a look at what is missing or what mistake i have made.?
Here is my code:
function passCheck() {
var passexp = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var password = document.getElementById("password");
if (password != "") {
if (!password.match(passexp)) {
document.registration.password.focus();
document.getElementById('error2').innerHTML = "Password should be atleast 8 character long and must contain at least one digit,at least one lower case,at least one upper case.";
return false;
} else {
document.getElementById('error2').innerHTML = "";
return true;
}
} else {
document.registration.password.focus();
document.getElementById('error2').innerHTML = "Password can't be blank";
return true;
}
}
<label for="password">* Password </label>
<input type="password" name="password" placeholder="Password should be atleast 8 characters" id="password" size="40" required="required" onblur="return passCheck();"/>
<span id="error2"></span>
EDIT:
Hello,
In same form I have few other fields(viz. name,email,password,confirm password,username,mobile no, street, city, country(Select tag), gender(radio button).
and now my questions are or rather confusions are:
do I need to check if the field is empty(on both client side and server side) in spite of using 'required' attribute?
I have created new function for each of the field i am trying to validate(just like passCheck() which makes code unnecessarily lengthy. So here re-usability of code is not done. In what other way I can implement validation so as to achieve it. Its bit boring too to implement similar kind of logic or methods again and again with minor changes.
Javascript variable can not have same name as that of function name which contains that variable.? Why?
Because when I was trying to use same name,code didn't worked. But when I checked same code on jsfiddle.net it showed me an error for that variable.
Whats the purpose of using PHP functions like mysql_real_escape_string() for non text fields(select box and radio button). Here we are not allowing user to enter anything else but the already defined options only.
Is it good practice to keep one radio button checked for gender.?
I am storing gender in database as CHAR(1) which stores first character of Male/Female.
How to store same using ENUM.?
This:
var password = document.getElementById("password");
if (password != "") {
...assigns the HTML password input to the password variable, not the value of that input. (password != "") will always be true because password is not a string, it's a form element.
Try this instead:
var password = document.getElementById("password").value;
Below is a regular expression you can try.
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
The above regex will enforce these rules:
At least one upper case Alphabet
At least one lower case Alphabet
At least one digit
Minimum 8 in length
"^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[$#$!%?&])[A-Za-z\d$#$!%?&]{8,}"
The above regex will enforce these rules:
At least one upper case Alphabet
At least one lower case Alphabet
At least one digit
One Special character
Minimum 8 in length
Also Check Steve's answer regarding the form not working.
You need to make the distinction between the <input> element and the value it contains. The following snippet contains a few changes to your original code. In particular, the variable passwordValue contains the text content of the <input>, whereas passwordElement is the input itself. I also added in a .trim() to your test for whether the input is blank, as this catches input consisting of only whitespace before doing the regex match.
function passCheck() {
var passexp = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var passwordElement = document.getElementById("password");
var passwordValue = passwordElement.value;
if (passwordValue.trim() !== "") {
if (!passwordValue.match(passexp)) {
passwordElement.focus();
document.getElementById('error2').innerHTML = "Password should be atleast 8 character long and must contain at least one digit,at least one lower case,at least one upper case.";
return false;
} else {
document.getElementById('error2').innerHTML = "";
return true;
}
} else {
passwordElement.focus();
document.getElementById('error2').innerHTML = "Password can't be blank";
return true;
}
}
<label for="password">* Password </label>
<input type="password" name="password" placeholder="Password should be atleast 8 characters" id="password" size="40" required="required" onblur="passCheck()"/>
<span id="error2"></span>
As you asked in the comments about the !== operator, here is some explanation:
!== is the opposite operator to ===, which means that it does a strict comparison between the left hand side and the right hand side. This means that the type of the variable is important, as well as the value. For example 2 == "2" will evaluate to true, whereas 2 === "2" will evaluate to false. It is generally regarded as good practice to use the strict comparison as it communicates what you are trying to do more effectively. I changed != to !== in your code for this reason; it is not directly related to fixing your problem.
Just change your regex to,
^(?=.{8,})(?=.*?\d)(?=.*?[A-Z])(?=.*[a-z]).*?(?:(?!\s|\n)\W).*$
(?:(?!\s|\n)\W) ensures that the one character must be a non-word character but not of space or newline character.
DEMO
And this won't allow spaces or newline characters inside the password text box,
^(?=.{8,})(?=.*?\d)(?=.*?[A-Z])(?=.*[a-z])(?:(?!\s|\n)[\W\w])*$
DEMO

Form validation of numeric characters in JavaScript

I would like to perform form validation using JavaScript to check for input field only to contain numeric characters.So far, the validation checks for the field not being empty - which works fine.However, numeric characters validation is not working.I would be grateful for any help.Many thanks.
<script type="text/javascript">
//form validation
function validateForm()
{
var x=document.forms["cdp_form"]["univer_number"].value
if (x==null || x=="")
{
alert("University number (URN) field must be filled in");
cdp_form.univer_number.focus();
return false;
}
else if (is_valid = /^[0-9]+$/.test(x))
{
alert("University number (URN) field must have numeric characters");
cdp_form.univer_number.focus();
return false;
}
}
</script>
<input type ="text" id="univer_number" maxlength="7" size="25" name="univer_number" />
Rather than using Regex, if it must only be numerals you can simply use IsNumeric in Javascript.
IsNumeric('1') => true;
IsNumeric('145266') => true;
IsNumeric('abc5423856') => false;
You need invert your regular expression (add ^ inside [0-9]):
/^[^0-9]+$/
Your test condition is a bit strange:
else if (is_valid = /^[0-9]+$/.test(x))
Why have the redundant comparison to is_valid? Just do:
else if (/^[0-9]+$/.test(x))
Though the regex you are using will match numerals and only numerals - you need to change it to match anything that is not a numeral - like this /^[^0-9]+$/.
Better yet, get rid of the regex altogether and use IsNumeric:
else if (!IsNumeric(x))
On your line that says else if (is_valid = /^[0-9]+$/.test(x)), you're doing a simple assignment instead of testing that it is actually matching the regex.
Your pattern will still accept this input <b>##$##123 or ad!##12<b>. Use this pattern I created:
/[a-zA-Z-!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?]/
This pattern will check if it is alphabetic and special characters.
You need to test for the negation of the RegExp because you want the validation to alert upon failure, so just add ! in front of it:
else if (is_valid = !/^[0-9]+$/.test(x))
See example →
I know this is an old post but I thought I'd post what worked for me. I don't require the field to be filled at all but if it is it has to be numerical:
function validateForm()
{
var x=document.forms["myformName"]["myformField"].value;
if (/[^0-9]+$/.test(x))
{
alert("Please enter a numerical amount without a decimal point");
myformName.myformField.focus();
return false;
}
}

Categories

Resources