Hi All ,
How validate textbox using Javascript ? condition is only allow
Positive Number -> 45
Negative Number -> -45
Thanks in advance ,
Karthik.K
Hi All ,
How validate textbox using Javascript ? condition is only allow
Positive Number -> 45
Negative Number -> -45
Thanks in advance ,
Karthik.K
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Daniel WrightRank #2,947 · 489 reputationPosted May 7, 2025, 11:25 PM EDT
Hi Karthik.K,
To only allow positive and negative numbers in a textbox using JavaScript, you can utilize a validation function that ensures the input is numeric and meets your specified criteria. Here is a simple example of how you can achieve this:
// JavaScript function to restrict input to numbers and allow negative numbers function validateNumberInput(event) { const key = event.key; const isNumber = /^\d$/.test(key); const isMinusSign = key === '-' && !event.target.value.includes('-'); if (!isNumber && !isMinusSign) { event.preventDefault(); } }In this script, the `validateNumberInput` function restricts the input to only allow digits (numbers) and a single minus sign for negative numbers. You can attach this function to your textbox input field like this:
By binding this function to the `onkeypress` event of your textbox, it will prevent users from entering anything other than numbers and a single minus sign for negative numbers.
Feel free to adjust the validation logic further based on your specific requirements, such as handling decimal numbers or refining the formatting of negative numbers. I hope this helps you achieve the desired validation for your textbox. If you have any more questions or need further assistance, feel free to ask!