I have a form that accepts name, phone no. Currently, I have done validation for non empty fields. I want to add validation for name (alphabets) and phone no.(numbers).
My current code is given below. On submitting the form, I will be calling validateform() function:
function validateform()
{
var str= true;
document.getElementById("name").innerHTML="";
if(document.frm.name.value=="")
{
document.getElementById("name").innerHTML="Please enter Name";
str=false;
}
return str;
}
The value entered for name should be only alphabets. If not, I want to show the message "enter only alphabets". How should I do it?
/*mobile number of 10 digits */
var digit=10;
var pattern=/[0-9]{digit}/;
if(!pattern.match ( phoneno ) )
alert("not a valid number");
As noted in the comments, you can try something like this:
var rule = /^[a-zA-Z]*$/;
if(rule.test(document.frm.name.value)) {
// this contains only letters !
}
You could use regex to achive what you're trying to do.
function validatePhonenumber(value) {
var regexp = /^[0-9]+?$/;
return regexp.test(value);
}
function validateAlphabet(value) {
var regexp = /^[a-zA-Z ]*$/;
return regexp.test(value);
}
var alphaExp = /^[a-zA-Z]+$/;
if(!document.frm.name.match(alphaExp))
{
document.getElementById("name").innerHTML="Please enter only alphabets";
str=false;
}
var numExp = /^[0-9]+$/;
if(!document.frm.phone.match(numExp))
{
document.getElementById("phone").innerHTML="Please enter only numbers";
str=false;
}
With this you don't need to check for empty input. If you want to handle empty input separately, replace + with a * in the regexes.
function alphanumeric(inputtxt)
{
var letters = /^[0-9a-zA-Z]+$/;
if(inputtxt.value.match(letters))
{
alert('Your registration number have accepted : you can try another');
document.form1.text1.focus();
return true;
}
else
{
alert('Please input alphanumeric characters only');
return false;
}
}
See more here.
Related
I'm trying to do a validation including these requires:
Allow to insert a name with space between , example: "Nicolas Tesla"
Not allow to insert spaces or numbers , example: " " or "12354"
I have this function but i don't know if i'm doing right:
function ValidName(){
var regex = /^[a-zA-Z]$/;
var name = $("#txtNome").val();
if(name == ""){
alert("Please, type your name.");
name.focus();
return false;
}
else if(name =! name.regex){
alert("Please, type your name.");
name.focus();
return false;
}
}
The first "if" is working , if i don't type anything then alert comes out , but the second one isn't and i don't know if i'm doing right , in fact i don't know what i'ma doing.
First of all, modify your regex so that it accepts strings with at least one character separated with one space with another set of one or more characters:
var regex = /^[a-zA-Z]+(\s[a-zA-Z]+)?$/;
That will save you the first "if" statement.
Then, to check if your regex match, you should use RegExp.prototype.test
your code would then look like
function ValidName(){
var regex = /^[a-zA-Z]+(\s[a-zA-Z]+)?$/;
var $name = $("#txtNome");
if(!regex.test($name.val())){
alert("Please, type your name.");
$name.focus();
return false;
}
return true;
}
My java-script regex validation requires the following condition.
Accept only alphabet value
Do not accept only numeric value
Do not accept only special characters
Accept combination of alphanumeric and special character value
I wrote following code to achieve it
function validateAlphaNumChar(str) {
var filter = /^[ A-Za-z0-9_##./#&+-]*$/;
if (filter.test(str)) {
return true;
}
else {
return false;
}
}
and I also tried different regex but never achieved the desired result.
Please do help me with the proper regex for my validations.
Thank You
Since, It is necessary to have alphabets in your string, simply check for that
function validateAlphaNumChar(str) {
var filter = /^[ A-Za-z0-9_##./#&+-]*$/;
var filterAlphabets = /^[ A-Za-z]*$/;
if (filter.test(str)) {
if ( filterAlphabets.test(str)){
return true;
}
else{
return false; }
}
else {
return false;
}
}
This is assuming that a combination of numbers and special characters is not allowed
If i understood the question right it should be like this
Check if it contains only numbers
Check if it contains only special symbols
function validateAlphaNumChar(str) {
var filterABC = /^[A-Za-z]*$/;
var filterNUM = /^[0-9]*$/;
var filterSPEC = /^[_##./#&+-]*$/;
if (filterNUM.test(str)) {
return false;
} else if(filterSPEC.test(str)) {
return false;
} else {
return true;
}
}
document.getElementById("demo").innerHTML = validateAlphaNumChar("A#");
<p id="demo"></p>
I have a string which is of format 245545g65.
var value = "245545g65"
var last3Letters = value.substring(7,9); // abc
Now I want to validate whether the last three letters contains only alphabets, if it is alphabet , i want to alert it.how to alert g?
how do i do this?
assuming that "contains only alphabets" means the last three characters are a combination of the letters a-z:
var str = '245545g65';
if (/[a-z]{3}$/.test(str)){
// last three characters are any combinations of the letters a-z
alert('Only letters at the end!');
}
you can use RegEx and compare length
var re = new RegExp("[^0-9]*", "g");
var newlast3Letters =last3Letters.replace(re,"");
if(newlast3Letters.length!=last3Letters.length)
{
alert("not all alphabets");
}
else
{
alert("all alphabets");
}
you can use isNaN to check weather s string is number
if (!isNan(last3Letters))
alert(last3Letters + ' is number.')
else
alert(last3Letters + ' is not number.')
You can also do this:
var value = "245545g65"
if(value.slice(value.length-3).search(/[^a-z]/) < 0) {
alert("Just alphabets");
} else {
alert("Not just alphabets");
}
Easy:
var alpha = /^[A-z]+$/;
alpha.test(last3Letters);
This will return a boolean (true/false). Stolen from here.
I know its good to use serverside validation for security, except this is just to get my head around validation.
My efforts so far have amounted to the following
function validateUser()
{
var x=document.forms["myForm"]["email"].value;
var y=document.forms["myForm"]["password"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
var uppercase = password.match(/[A-Z]/)
var lowercase = password.match(/[a-z]/g)
var number = password.match(/[0-9]/g)
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address or password");
return false;
}else{
alert("Valid Email Address and Password");
return true;
}
}
Basically, I need an alert box to pop up when the password doesn't have at least 1 lowercase, uppercase and a number. So far my code is just throwing an error when the email is in the wrong format. What do I add to the if statement to check the password characters?
Thanks in advance,
James
Few issues we have in your current implementation:
a. The error you're likely getting is that password is undefined.
Right now you're doing:
var y=document.forms["myForm"]["password"].value;
but you refer to it as "password" further on:
var uppercase = password.match(/[A-Z]/)
var lowercase = password.match(/[a-z]/g)
change the var y to:
var password=document.forms["myForm"]["password"].value;
b. To validate email, you should use a Regex such as:
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var isValidEmail = re.test(email);
c. To check for the password rules, you should just rely on the regular expressions you have in place already (and strip out the atpos, dotpos usage - that makes it much more complicated than it even needs to be).
Example:
var email='me#mailinator.com';
var password='test-P1assword';
var hasUpper = password.match(/[A-Z]/)
var hasLower = password.match(/[a-z]/g)
var hasNumber = password.match(/[0-9]/g)
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var isValidEmail = re.test(email);
if (isValidEmail && hasUpper && hasLower && hasNumber) {
alert("Valid Email Address and Password");
return true;
} else {
alert("Not a valid e-mail address or password");
return false;
}
JSFiddle example, complete with Regex to validate email AND password: http://jsfiddle.net/4hH3T/2/
The regex was taken from: Validate email address in JavaScript?
you can use regex to validate.
var reg=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/;
var isValid=reg.test(inputemail);
I want to check that if my username contains space so then it alert so i do this it work but one problem i am facing is that if i give space in start then it does not alert.I search it but can't find solution, my code is this
var username = $.trim($('#r_uname').val());
var space = " ";
var check = function(string){
for(i = 0; i < space.length;i++){
if(string.indexOf(space[i]) > -1){
return true
}
}
return false;
}
if(check(username) == true)
{
alert('Username contains illegal characters or Space!');
return false;
}
Just use .indexOf():
var check = function(string) {
return string.indexOf(' ') === -1;
};
You could also use regex to restrict the username to a particular format:
var check = function(string) {
return /^[a-z0-9_]+$/i.test(string)
};
You should use a regular expression to check for a whitespace character with \s:
if (username.match(/\s/g)){
alert('There is a space!');
}
See the code in action in this jsFiddle.
why you don't use something like this?
if(string.indexOf(space) > -1){
return true
}