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>
Related
I have a regex which checks the inputText is in valid url format or not.
And working almost good:
checkUrlFormat() {
const pattern = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}
But i need to make that pattern shorter so I have written a regexp in https://www.debuggex.com/#cheatsheet as
(((http|https)(://))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]
but it is in javascript format and i could not find how to use that string with the code above. When i directly copy paste it, it is giving syntax error. How can i combine them.
checkUrlFormat() {
const pattern = /^(((http|https)(:\/\/))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}
I am trying to validate a string where the first character must be an 'x' and the remaining characters must be numerical. For example:
x1234 == true;
k1234 == false;
x12k4 == false;
1x123 == false;
Here is my code:
function isValidCode(code){
var firstLetter = code.substring(0,1);
var remainingCode = code.substring(1);
var validCode = false;
// Debugging
console.log(firstLetter);
console.log(remainingCode);
if(firstLetter == 'x'){
validCode = true;
}
if(isNumeric(Number(remainingCode))){
validCode = true;
}
}
I've debugged my isNumeric() function, so I'm 99.9% sure the issue isn't there, but here it is just in case:
function isNumeric(numberIn)
{
var returnValue = true;
if (isNaN(numberIn) || isNaN(parseInt(numberIn, 10)))
{
returnValue = false;
}
return returnValue;
}
I've tried several things such as reversing my logic where I start with the given condidtion being true and then checking if(!(firstLetter == 'x')) I've tried == and ===and I've tried casting the remaining portion of the code with Number() , +() and not casting it at all, but none of these seeem to do the trick. The console does log the proper first character and remaining characters in the code so I'm not sure what is wrong.
You can use a regular expression test:
function isValidCode(code) {
return /^[a-z]\d+$/.test(code);
}
I am making an assumption that a lower case letter is required, followed by at least one digit.
To match only only the letter 'x', use:
function isValidCode(code) {
return /^x\d+$/.test(code);
}
You can use RegExp /^x(?=\d+$)/ to match x at beginning of input followed by digits followed by end of input
var arr = ["x1234"
, "k1234"
, "x12k4"
, "1x123"];
var re = /^x(?=\d+$)/;
arr.forEach(function(str) {
console.log(`${str}: ${re.test(str)}`)
})
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.
I've got this JavaScript function:
function emailaddresscheck() {
var emailregex = new RegExp("[A-Z0-9._%+-]+#[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
var emailstring = $("#email-address").val();
if (emailregex.test(emailstring)) {
$("#email-address-check").fadeIn(100);
return true;
}
else if ($("#email-address").val().length <= 5) {
$("#email-address-check").fadeOut(100);
return false;
}
}
The if condition is firing if I have a simple string in the RegExp constructor but this more complex regex isn't working.
Where am I going wrong?
UPDATE:
This is the finished working code:
function emailaddresscheck() {
var emailregexp = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\\.(?:[A-Za-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$");
var emailstring = $("#email-address").val();
if (emailregexp.test(emailstring) === true) {
$("#email-address-check").fadeIn(100);
return true;
}
else if (emailregexp.test(emailstring) === false) {
$("#email-address-check").fadeOut(100);
return false;
}
}
When you create a regex with the RegExp constructor you need to double escape special characters since they are inside a string.
new RegExp("[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
-^-
Or just use a literal regex:
/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)/
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
}