My validation accepts only alphabets. I want allow spaces as well.
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z]+$/);
});
What change needs to be done here?
Instead of the below regex:
/^[a-zA-Z]+$/
Use this:
/^[a-zA-Z\s]+$/
This will also take the space.
Just leave a space or use \s in your regex:
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z\s]+$/);
// -- or leave a space here ^^
});
jQuery.validator.addMethod("lettersonlys", function(value, element) {
return this.optional(element) || /^[a-zA-Z ]*$/.test(value);
}, "Letters only please");
Use pattern: /^[a-zA-Z ]*$/
Your validation is proper. You just need to change regex /^[a-zA-Z ]*$/
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z ]*$/);
});
**
I have tried above but space was an issue in above given regex
/^[a-zA-Z\s]+$/ and /^[a-zA-Z]+$/. The Below worked for me:
**
$('.name-val').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z ]+$");
var strigChar = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(strigChar)) {
return true;
}
return false
});
Please use these pattern for validation.
var pattern = /^[a-zA-Z ]+$/;
if(!pattern.test(name) && name !=''){
return false;
}
Related
I need to modify this function to work properly. It is supposed to restrict everything but the alphabet, spaces, and apostrophes. Currently it is still restricting apostrophes. I'm assuming the pattern ' \ _ ' is referring to ALL special characters. How would I insert an exception in to this function?
function NameNotNA (s) {
var pattern;
if (s.toUpperCase().indexOf('N/A') != -1){
//console.warn('failed in n/a');
return false;
}
// Eliminate possibility of digits
pattern = /\d/;
if (s.match(pattern) != null) {
//console.warn('failed in \d');
return false;
}
pattern = /\_/;
if (s.match(pattern) != null) {
//console.warn('failed in \_');
return false;
}
s = s.replace(/ /g, '');
if (s.match(/\W/) != null) {
return false;
}
return true;
}
function nameNotNA (s) {
return s.replace(/[^\w\s']/g, '');
}
For regex, I like using this tool to understand exactly what's happening. Also, it's good to keep your function names lowerCamelCase unless it's a Class.
I am using following code to allow only a-z, A-z, space, newline, tab.
But it doesn't allow tab key.
Here is my javascript code.
// Filter invalid characters in title
$('#p_title').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9 \b\n\r\f\t\v]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
You need to double escape all escape sequences for constructing RegExp object. However better to just use regex literal in your case:
var regex = /^[a-zA-Z0-9 \b\n\r\f\t\v]+$/;
Full code:
$('#p_title').keypress(function (e) {
var regex = /^[a-zA-Z0-9 \b\n\r\f\t\v]+$/;
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
Try use .on instead .keypress:
http://jsfiddle.net/z9wvfj1e/1/
// Filter invalid characters in title
$('#p_title').on('keydown', function (e) {
if (e.keyCode >=37 && e.keyCode <=40) return true;
var regex = new RegExp("^[a-zA-Z0-9 \b\n\r\f\t\v]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
console.log(e);
return true;
}
e.preventDefault();
return false;
});
Something like this sounds like all you need:
$('#p_title').keypress(function (e) {
return /[a-z]|\s|\r?\n|\t/i.test(String.fromCharCode(e.which));
});
I am doing a case-insensitive check for whether the character entered is a letter OR a space OR a newline OR a tab.
Furthermore, you don't need to check for e.charCode with jQuery because:
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
https://api.jquery.com/event.which/
I have been looking around but can't find a way to do this. I really like the jquery validate script and I was wondering if there was a way to check to see if a field contains a comma and not validate if there is no comma.
You can use .inArray() method as it is described here
You should split your string, and then you can use this:
var found = $.inArray(',', categories)
if(found == -1) alert("Error!")
If you are referring to the jquery validate plugin:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
$("#input").rules("add", { regex: "," })
not familiar with jquery validate but str.indexOf returns the position where something appears in a string, -1 means it doesnt. check a string for a comma like this :
if (yourString.indexOf(',') > -1) {
validate();
}
I am trying to validate the textbox which has to allow space character only when followed by any alphabetic character. My code fails when only a space character is inserted. What is the mistake in my code. Suggestions pls..
javascript :
function validate() {
var firstname = document.getElementById("FirstName");
var alpha = /^[a-zA-Z\s-, ]+$/;
if (firstname.value == "") {
alert('Please enter Name');
return false;
}
else if (!firstname.value.match(alpha)) {
alert('Invalid ');
return false;
}
else
{
return true;
}
}
view:
#Html.TextBoxFor(m => m.FirstName, new { #class = "searchbox" })
<button type="submit" onclick="return validate();">Submit</button>
Conditions I applied :
Eg: Arun Chawla - condition success
Eg: _ - condition fails (should not allow space character alone)
try following regex
var alpha = /^[a-zA-Z-,]+(\s{0,1}[a-zA-Z-, ])*$/
First part forces an alphabetic char, and then allows space.
May be using the "test" method like this:
/^[a-zA-Z-,](\s{0,1}[a-zA-Z-, ])*[^\s]$/.test(firstname)
Only returns true when it's valid
Here's a link
I found Akiross's answer to be the best fit for me.
([a-z] ?)+[a-z]
This will allow the space between every character,number and special character(#).
pattern to be followed:
['', [Validators.email,
Validators.pattern('^[[\\\sa-z 0-9._%+-]+#[\\\sa-z0-9.-]+\\.[\\\sa-z]{2,4}]*$')]],
output:
e 2 # 2 g . c o
if(!/^[A-Za-z\s]+$/.test(name)) {
errors['name'] = "Enter a valid name"
}
Consider a JavaScript method that needs to check whether a given string is in all uppercase letters. The input strings are people's names.
The current algorithm is to check for any lowercase letters.
var check1 = "Jack Spratt";
var check2 = "BARBARA FOO-BAR";
var check3 = "JASON D'WIDGET";
var isUpper1 = HasLowercaseCharacters(check1);
var isUpper2 = HasLowercaseCharacters(check2);
var isUpper3 = HasLowercaseCharacters(check3);
function HasLowercaseCharacters(string input)
{
//pattern for finding whether any lowercase alpha characters exist
var allLowercase;
return allLowercase.test(input);
}
Is a regex the best way to go here?
What pattern would you use to determine whether a string has any lower case alpha characters?
function hasLowerCase(str) {
return str.toUpperCase() != str;
}
console.log("HeLLO: ", hasLowerCase("HeLLO"));
console.log("HELLO: ", hasLowerCase("HELLO"));
also:
function hasLowerCase(str) {
return (/[a-z]/.test(str));
}
function hasLowerCase(str) {
return str.toUpperCase() != str;
}
or
function hasLowerCase(str) {
for(x=0;x<str.length;x++)
if(str.charAt(x) >= 'a' && str.charAt(x) <= 'z')
return true;
return false;
}
Another solution only match regex to a-z
function nameHere(str) {
return str.match(/[a-z]/);
}
or
function nameHere(str) {
return /[a-z]/g.test(str);
}