Skip to content Skip to sidebar Skip to footer

Quick Regex With Alert

I wish to allow only numbers and periods ( but only one period ) no commas, no alpha. So user can type 300.00 I also need to trigger alert, if possible ( not a windows alert just a

Solution 1:

For the regular expression, try this: ^\d+\.?\d+$.

It will match a string which starts with one or more digits, optionally followed by a single period, which is then followed by one or more digits which form the end of the string.

To test the value, within your validation code do this:

//Add event handler using W3C event bindingdocument.getElementById("price").addEventListener("blur", function()
{
   //Test the value of the input field and whether it matches the regular expression,     where val is the value extracted from the fieldif(!this.value.match(/^\d+\.?\d+$/))
  {
    alert("Validation error, must be numeric");
  }
}, false);

EDIT: note that if you wish to add event binding in IE you can either use traditional event binding document.getElementById("price").onblur = function(){...} or IE's event binding model: document.getElementById("price").attachEvent("onblur", function(){...}); note though that using attachEvent does not assign the this object within the callback function, so you will need to get the event object (window.event) and then extract the element using window.event.srcElement. See http://www.quirksmode.org/js/events_advanced.html for reference

Solution 2:

I guessvar result=this.value.match(/[0-9]+\.?[0-9]+/); if(result==null){alert}

Post a Comment for "Quick Regex With Alert"