'How to star part of text field? Like 1234 **** **** 1234

enter image description here

While the user is entering the credit card number, I want to star a certain part of the text field as above for security. How can I do it?



Solution 1:[1]

I don't think there's a default HTML keyword for this, here I made a simple JS override input for you, see if it suits your needs:

HTML:

<input type="text" id="text1" />

JS:

var ccnum = "";
var displaytext = "";

$(document).ready(function() {
    $("#text1").keydown(function(e) {
        if (e.which == 8)
        {
            event.preventDefault();
            ccnum = ccnum.substring(0, ccnum.length - 1);
            refineText();
        }
    });
    
    $("#text1").keypress(function(e) {
        event.preventDefault();
    
        var ch = String.fromCharCode(e.which);
        ccnum += ch;
        refineText();
        
        $("#text1").val(displaytext);
    });
    
    $("#text1").keyup(function(e) {
        if (e.which == 8)
        {
            $("#text1").val(displaytext);
        }
    });

});

function refineText()
{
    displaytext = ccnum;
    if (ccnum.length > 4)
    {
        displaytext = displaytext.substring(0, 4);
        var maxlength = ccnum.length - 4;
        if (maxlength > 8) maxlength = 8;
        
        for (i = 0; i < maxlength; i++)
            displaytext += "*";
        
        if (ccnum.length > 12)
            displaytext += ccnum.slice(12);
    }
}

Solution 2:[2]

I found the Solution, first of you have to add Delegate for that TextField, After Adding TextField you have to add below code,

func textFieldDidChangeSelection(_ textField: UITextField) {
    if (textField.text?.count ?? 0) > 4 && (textField.text?.count ?? 0) < 15{
        let firstFourElement = String(self.textFieldEmail.text?.prefix(4) ?? "")
        switch textField.text?.count ?? 0 {
        case 5:
            self.textFieldEmail.text = firstFourElement + " *"
        case 7:
            self.textFieldEmail.text = firstFourElement + " **"
        case 8:
            self.textFieldEmail.text = firstFourElement + " ***"
        case 9:
            self.textFieldEmail.text = firstFourElement + " ****"
        case 10:
            self.textFieldEmail.text = firstFourElement + " **** *"
        case 12:
            self.textFieldEmail.text = firstFourElement + " **** **"
        case 13:
            self.textFieldEmail.text = firstFourElement + " **** ***"
        case 14:
            self.textFieldEmail.text = firstFourElement + " **** **** "
        default:
            print("TEST")
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Almaz Hong
Solution 2 Vaibhav Khatri