How to character and Numeric values restrict in TextField Java - java

I have two questions regarding character and numeric values limitation. I have listening to focus lost events and validating Name (character) and Contact (numeric) TextFields.
1. How do I restrict numeric data less then 3 digits and not allow more then 13 digits.
Below is the coding of my contact TextField for numeric:
private void txt_contactFocusLost(java.awt.event.FocusEvent evt) {
if (txt_contact.getText().equals("")) {
} else {
String contact = txt_contact.getText();
Pattern pt6 = Pattern
.compile("^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]+$");
Matcher mh6 = pt6.matcher(contact);
boolean matchFound6 = mh6.matches();
if (!(matchFound6)) {
JOptionPane.showMessageDialog(null,
"* Enter the Numaric Values only *");
txt_contact.setText("");
txt_contact.requestFocus();
}
}
}
2. How do I restrict character data less then 3 character and not allow more then 30 characters.
private void txt_nameFocusLost(java.awt.event.FocusEvent evt) {
if (txt_name.getText().equals("")) {
error2.setText("Enter Full Name");
txt_name.setText("");
} else {
String name = txt_name.getText();
Pattern pt1 = Pattern.compile("^[a-zA-Z]+([\\s][a-zA-Z]+)*$");
Matcher mh1 = pt1.matcher(name);
boolean matchFound1 = mh1.matches();
if (!(matchFound1)) {
JOptionPane.showMessageDialog(null,
"* Enter the Character Values only *");
txt_name.setText("");
txt_name.requestFocus();
} else {
error2.setText("");
}
}
}

You can do something easier:
NumberFormat numF = NumberFormat.getNumberInstance();
numF.setMaximumIntegerDigits(13);
numF.setMinimumIntegerDigits(3);
JFormattedTextField THE_FIELD = new JFormattedTextField(numF);
(The same idea for characters)
Now, only numbers are allowed, with the specified length range.
Read more about it: NumberFormat and JFormattedTextField

in the pattern you can use the statement {n,m} n- to m- times
Duo to this you can build your pattern like this
for your charackter comparison
Pattern pt6=Pattern.compile("[a-zA-Z]{3,30}"); // it says, it should be 3-30 non Digits
for the numbers it is
Pattern pt6=Pattern.compile("\\d{3,13}"); // it says, it should be 3-13 Digits

For String
public boolean validateString(String data){
char [] chars = data.toCharArray();
if(chars.length < 3 || chars.length >13)
return false;
return true;
}
For Number
public boolean validateNumber(int number){
String data = number+"";
return validateString(data);
}

I'm using this one. very simple and easy
use the method that you need or both then call where you need pass your JTextField as parameter done...
public static void setNumericOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((!Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}
public static void setCharacterOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}

Related

Mask Some Char in a JTextField

I need to mask number when the user is typing so on the user UI, user should see a masked number but on the Java code I should get the entire number including masked char that is
what user should see 4545********9632
but on Java code (behind) I should get the entire number including masked char. I have tried MaskFormatter with JFormattedTextField and does not work, it displays the entire number.
try {
MaskFormatter mask=new MaskFormatter("####********####");
JFormattedTextField js=new JFormattedTextField();
mask.install(js);
} catch (ParseException ex) {
Logger.getLogger(Masker.class.getName()).log(Level.SEVERE, null, ex);
}
Here is my sudgestion,
class ACustomJEditText extends JTextField{
ArrayList<String> realText=new ArrayList<String>();
String displayText="";
public ACustomJEditText() {
// TODO Auto-generated constructor stub
super();
addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
// DELETE TEXT on backspace
if(e.getKeyCode()==KeyEvent.VK_BACK_SPACE) {
if(realText!=null && realText.isEmpty()==false) {
realText.remove(realText.size()-1);//remove character
}
turnRealTextToString();
//set the display text here
setText(displayText);
return;
}
//avoid any input if string actually string size is greater than 16
if(realText.size()==16) {
setText(displayText);
return;
}
//other keys should now be added to the input for only numbers
try{
int input=Integer.parseInt(e.getKeyChar()+"");
//add int to realtext
realText.add(input+"");
//turn real text to ####********#### string
turnRealTextToString();
setText(displayText);
}catch (Exception ex) {
// Other keys fail.
setText(displayText);
}
}
private void turnRealTextToString() {
String result="";
for(int i=0;i<realText.size();i++) {
if(i>3 && i<12) {
result+="*";
}else {
result+=realText.get(i);
}
}
String realDisplay=realText.toString();
System.out.println("DISPLAY: "+result+" REAL: "+getRealText());
//set result to display text
displayText=result;
setText(displayText);
}
});
}
//get the actual real text
public String getRealText() {
StringBuilder real=new StringBuilder();
realText.forEach(text->{
real.append(text);
});
return real.toString();
}
}
Should work like magic.
You can use regex:
var cardnumber = '4567 6365 7987 3783';
var first4 = cardnumber.substring(0, 4);
var last5 = cardnumber.substring(cardnumber.length - 5);
mask = cardnumber.substring(4, cardnumber.length - 5).replace(/\d/g,"*");
console.log(first4 + mask + last5);
or if you can try something like this:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<input class="form-control" id="myinput" data-length="12" name="name">
</body>
</html>
<script>
let initial = 4;
let maskChars = 6;
let realNumber = "";
$(function() {
$('#myinput').keyup(function(e) {
realNumber += this.value[this.value.length-1];
if (this.value.length >= initial && this.value.length <= initial + maskChars) {
this.value = this.value.slice(0, -1) + '*';
}
});
});
</script>
This I how I worked on JS. The idea is the same. You can replace charachters with * if the length is greater than you desired digit lengths. I haven't tried this Java code. For more you can visit this link:
https://www.javacodeexamples.com/mask-part-of-string-example-java/878
package com.javacodeexamples.stringexamples;
import org.apache.commons.lang3.StringUtils;
public class MaskStringExample {
public static void main(String[] args) throws Exception {
String str = "1234567812345678";
//mask first 4 characters
System.out.println( maskString(str, 0, 4, '*') );
//mask everything but last 4 digits
System.out.println( maskString(str, 0, 12, '*') );
//mask everything
System.out.println( maskString(str, 0, str.length(), '*') );
//mask everything but first and last 4 digits
System.out.println( maskString(str, 1, 12, '*') );
}
private static String maskString(String strText, int start, int end, char maskChar)
throws Exception{
if(strText == null || strText.equals(""))
return "";
if(start < 0)
start = 0;
if( end > strText.length() )
end = strText.length();
if(start > end)
throw new Exception("End index cannot be greater than start index");
int maskLength = end - start;
if(maskLength == 0)
return strText;
String strMaskString = StringUtils.repeat(maskChar, maskLength);
return StringUtils.overlay(strText, strMaskString, start, end);
}
}

How to validate a Jtextfield to only allow letters in Java?

Trying to make this field only allow letters and there is an error on the " (c !='[a-zA-Z]+') " saying invalid character constant
textField_CustomerFirstName = new JTextField();
textField_CustomerFirstName.setBounds(152, 100, 273, 22);
textField_CustomerFirstName.setColumns(10);
contentPane.add(textField_CustomerFirstName);
textField_CustomerFirstName.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
// allows only numbers and back space
char c = e.getKeyChar();
if ( ((c !='[a-zA-Z]+') && (c != KeyEvent.VK_BACK_SPACE)) {
e.consume(); // ignore event
}
}
});
First, there is a difference between event.getKeyChar() and event.getKeyCode().
Second, you can use the static methods in java.lang.Character, and I believe you may be after the following:
int code = e.getKeyCode();
char c = e.getKeyChar();
if(!Character.isLetter(c) && code!=KeyEvent.VK_BACK_SPACE) {
e.consume(); // ignore event
}
You may also want to investigate whether Character.isAlphabetic is suitable for your purposes.

how to get calculator to accept new numbers after equal sign is pressed? java

i am doing an exercise to create a simple calculator in java.
i want the calculator to keep taking numbers after the equal sign is pressed. so if i press "10+10 =" the result will be 20, and if I want to press "+1 = " and the result will be 21. or if I want to subtract as well.
my code is below. im sure the change has to be made to the "equals" portion of the code but i am unsure where/how to begin.
public int getDisplayValue()
{
return displayValue;
}
public void numberPressed(int number)
{
currentValue = (currentValue * 10) + number;
displayValue = currentValue;
}
private void applyPreviousOperation()
{
if (previousOp == '+')
{
heldValue = heldValue + currentValue;
displayValue = heldValue;
}
else if (previousOp == '-')
{
heldValue = heldValue - currentValue;
displayValue = heldValue;
}
else {
heldValue = currentValue;
}
}
public void plus()
{
applyPreviousOperation();
previousOp = '+';
currentValue = 0;
}
public void minus()
{
applyPreviousOperation();
previousOp = '-';
currentValue = 0;
}
public void equals()
{
applyPreviousOperation();
previousOp = ' ';
currentValue = 0;
heldValue = 0;
}
public void clear()
{
displayValue = 0;
previousOp = ' ';
}
}
You need to define your question more clearly.
what's the calculator flow should be. You describe an operation that contradicts a simple a+b.
It really matters how you input the numbers, If for example the very first operation is texted "a+b" ,"a-b" .... than you can keep it as currentValue.
than next opperations will be calculated against currentValue.
Have a variable called defaultOperand. When the equals button is pressed, update the defaultOperand variable with the output of the operation. It becomes the default left side operand. If an operation is inputted without a left side operand, then use the value in the defaultOperand as the default left hand operand.

How would I get a specific number range from a textfield?

I'm currently working on a search method in school and I'm stuck in a newbie mistake.
I havent been programming for long and I tried searching the internet for solutions but couldnt find any. I would need to get a number range from 1-10 from the textfield and then put it as an int. Once I've done that I would have to send it to my search method which I am working on. Thanks in advance peeps.
String Value = txfSort.getText();
int NumberValue = Integer.valueOf(Value);
Probably you should first limit the input of textFields to nummeric values. You can help your self with question here: What is the recommended way to make a numeric TextField in JavaFX?
public class NumberTextField extends TextField
{
#Override
public void replaceText(int start, int end, String text)
{
if (validate(text))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (validate(text))
{
super.replaceSelection(text);
}
}
private boolean validate(String text)
{
return text.matches("[0-9]*");
}
}
Code by: Burkhard
Above code would automaticly check on entry if input is ok. So then you just check, if value is > 0 and < 10. If that is true you just call your method and use value of textField.
One way of doing described would be this:
int value = Integer.valueOf(txfSort.getText());
if(value > 0 && value < 10)
{
myMethod(value);
}
try that one:
textField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9')) // for numbers only
&& (caracter != '\b')) {
e.consume();
}
if (Integer.valueOf(textField.getText() + caracter) > 10) {
e.consume(); // if on the text field the numbers are bigger
// than 10, consumes the last number typed
}
}
});

Apply .addKeyListener to array of JTextFields

I wrote the code below. It checks input from a JTextField and ensures the user is typing in numbers. If not the box flashes red and the invalid character is removed.
The tipArray[] is an array of JTextFields that I add to the JFrame with a loop.
How can I apply the following code to every possible array (tipArray[0], tipArray[1] ....tipArray[6])?
tipArray[6].addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
char keyChar = e.getKeyChar();;
char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!##$%^&*()[,]{}<>_+=|\"':;?/ ".toCharArray();
for (int i = 0; i < badCharArray.length; i++) {
if (badCharArray[i] == keyChar) {
tipArray[1].setBackground(Color.RED);
}
}
}
#Override
public void keyReleased(KeyEvent e) {
if (tipArray[6].getBackground() == Color.RED) {
if (tipArray[6].getText() != "0"){
String removeLastLetter = tipArray[1].getText().substring(0, tipArray[6].getText().length()-1);
tipArray[6].setText(removeLastLetter);
tipArray[6].setBackground(Color.WHITE);
}
}
}
});
The loops I have tried dont work:
for (int i = 0; i <= 6; i++) {
tipArray[i].addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
char keyChar = e.getKeyChar();;
char[] badCharArray = "abcdefghijklmnopqrstuvwxyz-`~!##$%^&*()[,]{}<>_+=|\"':;?/ ".toCharArray();
for (int x = 0; x < badCharArray.length; x++) {
if (badCharArray[x] == keyChar) {
tipArray[i].setBackground(Color.RED);
}
}
}
#Override
public void keyReleased(KeyEvent e) {
if (tipArray[i].getBackground() == Color.RED) {
if (tipArray[i].getText() != "0"){
String removeLastLetter = tipArray[i].getText().substring(0, tipArray[i].getText().length()-1);
tipArray[i].setText(removeLastLetter);
tipArray[i].setBackground(Color.WHITE);
}
}
}
});
}
^The above results in all of the variable i's after line "if (badCharArray[x] == keyChar) {" having a syntax error.
Change your counter in the for loop in the second one to be a different variable (z instead of i perhaps). You have a duplicate variable the way it is now (two i's). Also, it is recommended you use a DocumentListener, not KeyListener, for checking for invalid characters, as KeyListeners sometimes fail.

Categories

Resources