Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim spaces from form input?

Hello so i'm trying to trim the white spaces when the user enter spaces he get an error explaning that he should enter valid chars but if he used: ' test ' the same value is entered in the database do i need to trim that again in javascript ?

function validateForm()
{
    if(trim(document.insert.aname.value) ==="")
    {
      alert("Animal should have a name");
      document.insert.aname.focus();
      return false;
    }
}
function trim(value) {
    return value.replace(/^\s+|\s+$/g,"");
}

please can you help ? the input page is .JSP

like image 532
user1031152 Avatar asked Nov 14 '11 11:11

user1031152


People also ask

How do I remove whitespace from input?

The trim() method removes whitespace from both sides of a string.

How do you trim input value?

trim() method is used to remove the white spaces from both the ends of the given string. Return value: This method returns a new string, without any of the leading or the trailing white spaces. In this example the trim() method removes all the leading and the trailing spaces in the string str.

How do you trim in Javascript?

String.prototype.trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).


1 Answers

You're not actually trimming the input. You want this:

//store the input in a variable
var nameInput = document.insert.aname

function validateForm() {
    //Get the trimmed name
    var animalName = trim(nameInput.value)

    if(animalName) {
        //Update the form with the trimmed value, just before the form is sent
        nameInput.value = animalName
    }
    else {
         //Trimmed value is empty
         alert("Animal should have a name");
         nameInput.focus();
         return false;
    }
}

function trim(value) {
    return value.replace(/^\s+|\s+$/g,"");
}
like image 66
Eric Avatar answered Oct 12 '22 09:10

Eric