How to check textfield for whitespaces in jquery - javascript

I have a form. I want to put validation so that It will check if user enters white spaces or not. If its white spaces then show error. How could I do this?

In case you want to detect if there is any white space all through the user's input string,
var str = $("input").val();
if( str.indexOf(" ") !== -1 )
{
alert("bad input");
}
Example: http://jsfiddle.net/pYquc/

Use jQuery.trim(str) which remove the whitespace or tabs and you can validate.
http://api.jquery.com/jQuery.trim/

Try this usong javascript:
var v = document.form.element.value;
var v1 = v.replace("","");
if( v1.length == 0){
alert("error");
}
OR you can use following functions:
// whitespace characters
var whitespace = " \t\n\r";
/****************************************************************/
// Check whether string s is empty.
function isEmpty(s)
{ return ((s == null) || (s.length == 0)) }
/****************************************************************/
function isWhitespace (s)
{
var i;
// Is s empty?
if (isEmpty(s)) return true;
// Search through string's characters one by one
// until we find a non-whitespace character.
// When we do, return false; if we don't, return true.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (whitespace.indexOf(c) == -1) return false;
}
// All characters are whitespace.
return true;
}

function doValidations(){
if(jQuery.trim( $(".className").val())==""){
alert("error message");
return false;
}else{
return true;
}
}
<input type="submit" onclick="return doValidations();">

Related

How to validate textfield with 0 to 59, it will allow 1,2,3,*/59

I need to validate Textbox for this test cases.
It will allow 0 to 59 no characters and special character not allowed except *,/
It will allow 1,2,3,4 but 1,2,3,60 should not allow
It will allow /59 or 1,2,3,4,/59 but 1,2,3,5,*/59/19 should not allow
i tried,
var input = document.getElementById('configMinute').value;
//console.info("Else Called");
var slashPattern = "/";
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var getStringCheck = checkSpecialChar(input,specialChars);
if(getStringCheck==true){
// string = 1,2,3,*/10
// ,*/
var getStringValues = input.split(',');
var notAllowedCharPattern = "<>#!#$%^&()_+[]{}?:;|'\"\\.~`-=";
var allowedChar = checkSpecialChar(input,notAllowedCharPattern);
if(allowedChar==false){
console.info(getStringValues);
getStringValues.forEach(function(element){
//string = 1 2 3 */10
var validateSlash = checkSpecialChar(element,slashPattern);
if(element.startsWith("*")==true){
var newInput = element.split('/');
console.info("newInput: "+ element);
newInput.forEach(function(element) {
console.info("newInput Foreach: "+ element);
if(element=='*' || (element>=0 && element <=59)){
return true;
}
else{
alert("Please enter numbers between 0 to 59 or '*' ==>1");
document.getElementById('configMinute').focus();
return false;
}
});
}else{
console.info("* Else: "+ element);
if(element=='*' || (element>=0 && element <=59)){
return true;
}else{
alert("Please enter numbers between 0 to 59 or '*' ==>1");
document.getElementById('configMinute').focus();
return false;
}
}
});
}else{
alert ("File name has special characters \nAllowed Characters are *,/ ==>3");
document.getElementById('configMinute').focus();
return false;
}
}else if(input == '*' || (input>=0 && input <=59)){
return true;
}else{
alert("Please enter numbers between 0 to 59 or '*' ==>4");
document.getElementById('configMinute').focus();
return false;
}
Thanks in advance
You could try a regex like
(?:(?:^|,)(?:[1-5]?\d|\*?\/59)\b)+$
It matches the beginning of the line (^) or a , followed by either a number, 0-59, or /59 optionally preceded by a *. And this pattern can then repeat any number of times, until the end of the line.
See it here at regex101.

Removing < > symbols while typing in javascript

I have developed following code. But while typing i need to remove < > these two charectres. Its removing but it removing entire string when we type in middle. I donr want to remove entire string i want remove only < > while typing.
Enter your name:
<input type="text" id="UserC" onkeyup="rem()">
function rem() {
var spclChars = "<>"; // specify special characters
var content = document.getElementById("UserC").value;
for (var i = 0; i < content.length; i++) {
if (spclChars.indexOf(content.charAt(i)) != -1) {
document.getElementById("UserC").value = "";
return false;
}
}
}
You can use regex for that:
var str = 'hello<name>'
function rem(string) {
return string.replace(/<|>/g, '')
}
console.log(rem(str))
this will output helloname.
Use the below code it's working perfectly...
$(document).on('keypress', "#inputid", function(e) {
var check_val = $("#inputid").val();
if ((e.which == 60 || e.which == 62)) { // &lt ascii value is 60 and &gt ascii value is 62
console.log(check_val);
// $(this).attr("placeholder", "digits only");
// $(this).addClass("alert-danger");
$(this).val(check_val);
return false;
} else {
$(this).removeClass("alert-danger");
}
});

Add JavaScript min length validation to text field?

I'm currently using JavaScript code to validate a text field when the user types in letters a-z.
The script shows a tick if this is valid and a cross if its not. Now I am trying to add to the code to say check that the letters meet a minimum length of at least 4 characters, and if the min characters is met then show the tick and if the text is under the min character length show the cross.
How can I adjust my script to check the minimum length of the characters entered? Also can someone show me how I can allow '-' to be allowed in my validation?
script:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
if (reg.test(CnameField.value) == false)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
tried:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false)
if(input.value.length>!=len.min) return flase;
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
Almost there but you have a few syntax issues, so I've created an example test script for you:
function validateValue(value) {
var reg = /^[A-Za-z]+$/g;
var len = {min:4,max:60};
if (!reg.test(value)) {
console.log('didn\'t match regex');
return false;
}
if (value.length < len.min || value.length > len.max) {
console.log('incorrect length: ' + value);
return false;
}
console.log('correct length: ' + value);
return true;
}
validateValue('teststring');
Notice how I have set up the regex test, removing the == false? It's not needed because either false or array is returned. A true test will return true if anything other than null or false is returned.
Try this
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false) {
if(input.value.length<len.min)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
const validateCname = value => value.length < 4 ? `success message` : `error message`
function validateCname(value1)
{
var k = value1;
if(k.length<4){
//Your code if length is less than 4
}else{
//Your code if length is more than 4
}
}

Regular Expressions for phone numbers and mobiles doesn'nt work correctly

I have a function for validating telephone and mobile numbers. Here is part of my function:
function IsPhone(){
var mob = /09[123]\d{8}$/;
var phn = /0\d{10}$/;
for (var i = 0; i < edit_rows.length; i++) {
if (edit_types[i] == 5) {
var phon_val = document.getElementById('phone1').value;
if (phon_val != "") {
if (phon_val.match(mob))
return true;
else if (phon_val.match(phn)) {
if ((phon_val).length == 11)
return true;
}
else {
msg_req += "Invalid format";
return false;
}
}
}
}
return true;
}
But it accepts all of these:
009153842716
09153842716
001234567890
01234567890
what can I do?
I think adding a ^ at the beginning of your expression would fix it. Your current query would match strings like 'thisisaninvalidvalue09153842716'. Adding the ^ makes sure you don't start with invalid input.

Where in the code to validate a phone number, in JavaScript orRazor?

This is my first webpage in which I prompt the user for a phone number to add to a Do Not Call List database. Everything is working so far but I need to add the following, which I can do following the advice in this answer
stripping the input from all characters except digits
validating that the resulting string is 10 digits long
Then, when telling the user that the number was added to the list, I want to present it in the (999) 999-9999 format.
Where should I add all that code? Iside the #{ } block? In JavaScript? Razor?
Check phone number
function IsNumber(s) {
var i, currentCharacter;
for (i = 0; i < s.length; i++) {
// Check that current character is number.
currentCharacter = s.charAt(i);
if (((currentCharacter < "0") || (currentCharacter > "9"))) {
return false;
}
}
// All characters are numbers.
return true;
}
function TestInternationalPhone(strPhone) {
var bracket = 3,
openBracket,
phoneNumberOnly,
phoneNumberDelimiters = "()- ",
validWorldPhoneChars = phoneNumberDelimiters + "+",
minDigitsInIPhoneNumber = 10;
strPhone = SOS.StringHelper.Trim(strPhone);
if (strPhone.length === 0) {
return false;
}
if (strPhone.indexOf("+") > 1) {
return false;
}
if (strPhone.indexOf("-") != -1) {
bracket = bracket + 1;
}
if (strPhone.indexOf("(") != -1 && strPhone.indexOf("(") > bracket) {
return false;
}
openBracket = strPhone.indexOf("(");
if (strPhone.indexOf("(") != -1 && strPhone.charAt(openBracket + 2) != ")") {
return false;
}
if (strPhone.indexOf("(") == -1 && strPhone.indexOf(")") != -1) {
return false;
}
phoneNumberOnly = SOS.StringHelper.StripCharsInBag(strPhone, validWorldPhoneChars);
return (IsNumber(phoneNumberOnly) && phoneNumberOnly.length >= minDigitsInIPhoneNumber);
}

Categories